/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package web;

import java.util.List;
import views.CurrencyElement;
import views.DateElement;
import views.HighlightElement;
import views.LinkElement;
import views.TextElement;
import views.ViewElement;

/**
 *
 * @author Alejandro
 */
public class Formatter {
    private String formatString;

    private String escapeQuotes(String s) {
        return s.replaceAll("\"", "&quot;");
    }

    public String format(ViewElement ve) {
        ve.accept(this);
        return formatString;
    }

    public void formatText(ViewElement ve) {
        TextElement te = (TextElement) ve;
        formatString = te.getValue();
    }

    public void formatCurrency(ViewElement ve) {
        CurrencyElement ce = (CurrencyElement) ve;
        formatString = "$" + ce.getValue();
    }

    public void formatDate(ViewElement ve) {
        DateElement de = (DateElement) ve;
        String year = de.getValue().substring(0, 4);
        String month = de.getValue().substring(5,7);
        String day = de.getValue().substring(8, 10);
        formatString = day + "." + month + "." + year;
    }

    public void formatLink(ViewElement ve) {
        LinkElement le = (LinkElement) ve;
        StringBuilder extended = new StringBuilder();
        extended.append("<table><tr class=\"highlight\">");
        List<ViewElement> list = le.getExtended();
        for(ViewElement v: list) {
            extended.append("<td>");
            extended.append(v.getValue());
            extended.append("</td>");
        }
        extended.append("</tr></table>");
        String href = "index.jsp?table-selection=" + le.getIDR() + "&edit=Edit&row_" + le.getExtended().get(0).getValue() + "=on";
        formatString = "<span class=\"link\" onmouseover=\" tooltip(this,'" + escapeQuotes(extended.toString()) + "'); \" onmouseout=\"hide_info(this)\"><a class=\"in\" href=\""+href+"\">" + le.getValue() + "</a></span>";
    }

    public void formatHighlight(ViewElement ve) {
        HighlightElement he = (HighlightElement) ve;
        String href = "index.jsp?table-selection=" + he.getIDR() + "&edit=Edit&row_" + he.getHighlightId() + "=on";
        formatString = "<span class=\"link\" onmouseover=\" highlightTableRow("+he.getHighlightId()+", true); \" onmouseout=\" highlightTableRow("+he.getHighlightId()+", false); \"><a class=\"in\" href=\""+((he.getHighlightId() == 0) ? "":href)+"\">" + he.getValue() + "</a></span>";
    }
}
